package com.sky.controller;

import com.alibaba.fastjson.JSONObject;
import com.sky.bean.UpdateInfo;
import com.sky.bean.UpdateLog;
import com.sky.service.UpdateInfoService;
import com.sky.service.UpdateLogService;
import com.sky.utils.Constant;
import com.sky.utils.JsonHelper;
import com.sky.utils.Utils;
import org.apache.ibatis.annotations.Update;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by sun on 2017-05-22.
 */
@Controller
public class UpdateInfoController {
    private static Logger logger = Logger.getLogger(UpdateInfoController.class);

    @Autowired
    UpdateInfoService updateInfoService;

    @Autowired
    UpdateLogService updateLogService;

    @RequestMapping(value = "/updateinfo",produces="application/json;charset=UTF-8",
            method = RequestMethod.POST)
    @ResponseBody
    public String getUpdateInfo(HttpServletRequest request, @RequestBody String body)
    {
        UpdateLog updateLog = JSONObject.parseObject(body,UpdateLog.class);
        if(updateLog == null)
        {
            return JsonHelper.toJSONString(-1, Constant.JSON_PARSE_ERROR);
        }

        insertUpdateLog(request,updateLog);

        UpdateInfo currentVersionInfo = updateInfoService.getCurrentUpdateInfoService(
                updateLog.getChannelId(), updateLog.getAppId(), updateLog.getVersion()
        );
        UpdateInfo latestVersionInfo = updateInfoService.getLatestUpdateInfoService(
                updateLog.getChannelId(),updateLog.getAppId()
        );

        if(latestVersionInfo == null ||
                Utils.versionStringCmp( latestVersionInfo.getVersion(),updateLog.getVersion()) <= 0)
        {
            return JsonHelper.toJSONString(-1,"no update");
        }

        if(currentVersionInfo != null)
        {
            latestVersionInfo.setVersionTag(currentVersionInfo.getVersionTag());
        }

        return JsonHelper.toJSONString(0, Constant.OK,latestVersionInfo);
    }

    void insertUpdateLog(HttpServletRequest request,UpdateLog updateLog)
    {
        String ip = request.getHeader("X-Real-IP");
        if(ip == null) {
            ip = request.getRemoteAddr();
        }

        updateLog.setIp(ip);

        Date date = new Date();

        updateLog.setCreateTime(date);

        updateLogService.insertUpdateLogService(updateLog);
    }
}
